package com.ihome.android.http;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Locale;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRouteParams;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.text.TextUtils;

import com.ihome.android.common.ConfigUtil;
import com.ihome.android.mod.LoginMod;
import com.ihome.android.util.TripleDesUtil;
import com.ihome.android.util.Util;
import com.ihome.android.util.exception.ITVException;
import com.ihome.android.util.log.LogUtil;

/**
 * 各种http请求
 * 
 * @author Emerson
 * */
public class Http {
	private static final String	TAG						= Http.class.getSimpleName();

	private static final int	SET_CONNECTION_TIMEOUT	= 2500;
	private static final int	SET_SOCKET_TIMEOUT		= 5000;
	private static Http			http;
	private Context				context;

	private Http(Context context) {
		this.context = context;
	}

	/** 获取Https类实例对象 */
	public static Http getInstance(Context context) {
		if (null == http) {
			http = new Http(context);
		}
		return http;
	}

	/**
	 * Prior to Android 2.2 (Froyo), this class had some frustrating bugs. In
	 * particular, calling close() on a readable InputStream could poison the
	 * connection pool. Work around this by disabling connection pooling:
	 */
	private void disableConnectionReuseIfNecessary() {
		// Work around pre-Froyo bugs in HTTP connection reuse.
		if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
			System.setProperty("http.keepAlive", "false");
		}
	}

	private String initGetUrl(String url, List<NameValuePair> list) {
		
		if (url.contains("?")) {
			if(url.equals(ConfigUtil.SERVER_URL)){
				return url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));//实现加密
			}else{
//				return url + "?" + Util.encodeUrl(list, true);
				return url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));//实现加密

			}
			
//			return url + "&" + Util.encodeUrl(list, true);
		}
		else {
			
			if(url.equals(ConfigUtil.SERVER_URL)){
				return url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));//实现加密
			}else{
//				return url + "?" + Util.encodeUrl(list, true);
				return url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));
			}
//			return url + "?" + Util.encodeUrl(list, true);
		}
	}

	private String read(HttpURLConnection httpURLConnection) throws ITVException {
		String result = "";
		try {
			InputStream inputStream = null;
			int statusCode = httpURLConnection.getResponseCode();
			if (statusCode < 200 || 300 < statusCode) {
				inputStream = httpURLConnection.getErrorStream();
				LogUtil.d(TAG, "httpURLConnection.getContentLength() = " + httpURLConnection.getContentLength());
				if (null == inputStream || httpURLConnection.getContentLength() < 1)
					throw new ITVException(statusCode);
			}
			else {
				inputStream = httpURLConnection.getInputStream();
			}
			String contentEncoding = httpURLConnection.getContentEncoding();
			if (contentEncoding != null && contentEncoding.toLowerCase(Locale.US).indexOf("gzip") > -1) {
				inputStream = new GZIPInputStream(inputStream);
			}

			ByteArrayOutputStream content = new ByteArrayOutputStream();

			// Read response into a buffered stream
			int readBytes = 0;
			byte[] sBuffer = new byte[1024];
			while ((readBytes = inputStream.read(sBuffer)) != -1) {
				content.write(sBuffer, 0, readBytes);
			}

			String contentType = TextUtils.isEmpty(httpURLConnection.getContentType()) ? "" : httpURLConnection.getContentType();
			String charset = ((contentType.indexOf("charset=") != -1) && !TextUtils.isEmpty(charset = contentType.substring(contentType.indexOf("charset=") + 8))) ? charset : "UTF-8";
			LogUtil.v(TAG, "charset=" + charset);

			result = new String(content.toByteArray(), charset).trim();

			// LogUtil.v(TAG, "read = " + result);
		} catch (IOException e) {
			throw new ITVException(context, ITVException.HTTP_READ_IO_EXCEPTION);
		} finally {
			if (httpURLConnection != null)
				httpURLConnection.disconnect();
		}
		return result;
	}

	private InputStream getInputStream(HttpURLConnection httpURLConnection) throws ITVException {
		InputStream inputStream = null;
		try {
			int statusCode = httpURLConnection.getResponseCode();
			if (statusCode < 200 || 300 < statusCode) {
				inputStream = httpURLConnection.getErrorStream();
				LogUtil.d(TAG, "httpURLConnection.getContentLength() = " + httpURLConnection.getContentLength());
				if (null == inputStream || httpURLConnection.getContentLength() < 1)
					throw new ITVException(statusCode);
			}
			else {
				inputStream = httpURLConnection.getInputStream();
			}
			String contentEncoding = httpURLConnection.getContentEncoding();
			if (contentEncoding != null && contentEncoding.toLowerCase(Locale.US).indexOf("gzip") > -1) {
				inputStream = new GZIPInputStream(inputStream);
			}
		} catch (IOException e) {
			throw new ITVException(context, ITVException.HTTP_READ_IO_EXCEPTION);
		}
		return inputStream;
	}

	/**
	 * @param type
	 * @param url
	 * @param list
	 * @param conTimeOut
	 * @param socTimeOut
	 * @return
	 * @throws ITVException
	 */
	private HttpsURLConnection getHttpsURLConnection(String type, String url, List<NameValuePair> list, int conTimeOut, int socTimeOut) throws ITVException {

		LogUtil.i(TAG, "getHttpsURLConnection type        = " + type);
		LogUtil.i(TAG, "getHttpsURLConnection url         = " + url);
		LogUtil.i(TAG, "getHttpsURLConnection conTimeOut  = " + conTimeOut);
		LogUtil.i(TAG, "getHttpsURLConnection socTimeOut  = " + socTimeOut);

		disableConnectionReuseIfNecessary();

		if (null != list && "GET".equalsIgnoreCase(type)) {
			url = initGetUrl(url, list);
			LogUtil.i(TAG, "getHttpsURLConnection url         = " + url);
			list = null;
		}

		try {
			HttpsURLConnection connection = (HttpsURLConnection) (new URL(url)).openConnection(java.net.Proxy.NO_PROXY);
			if (null != list && !"GET".equalsIgnoreCase(type)) {
				for (NameValuePair nvp : list) {
					connection.setRequestProperty(nvp.getName(), nvp.getValue());
					LogUtil.i(TAG, "getHttpsURLConnection list        = " + nvp.getName() + "=" + nvp.getValue());
				}
			}

			SSLContext sslContext = SSLContext.getInstance("TLS");
			sslContext.init(new KeyManager[0], new MyTrustManager[] { new MyTrustManager() }, new SecureRandom());
			connection.setSSLSocketFactory(sslContext.getSocketFactory());
			connection.setHostnameVerifier(new AllowAllHostnameVerifier());

			conTimeOut = (1 > conTimeOut) ? SET_CONNECTION_TIMEOUT : conTimeOut;
			socTimeOut = (1 > socTimeOut) ? SET_SOCKET_TIMEOUT : socTimeOut;

			connection.setConnectTimeout(conTimeOut);
			connection.setReadTimeout(socTimeOut);

			connection.setRequestMethod(type); // 默认就是GET
			if ("post".equalsIgnoreCase(type)) {
				connection.setDoInput(true);
				connection.setDoOutput(true);
			}
			connection.setDefaultUseCaches(false);
			connection.setInstanceFollowRedirects(true);// 设置本次连接是否自动处理重定向

			// if (null != list && list.size() > 0) {
			// StringBuilder sb = new StringBuilder();
			// for (NameValuePair nvp : list) {
			// sb.append("\r\n").append(nvp.getName()).append(nvp.getValue()).append("&");
			// }
			// sb.deleteCharAt(sb.length() - 1);
			// connection.setRequestProperty("Content-Length",
			// String.valueOf(sb.toString().getBytes().length));
			// OutputStream os = connection.getOutputStream();
			// os.write(sb.toString().getBytes());
			// os.flush();
			// os.close();
			// }

			connection.connect();

			int statusCode = connection.getResponseCode();
			LogUtil.i(TAG, "getHttpURLConnection statusCode = " + statusCode);

			/** 手动重定向操作 */
			if (HttpURLConnection.HTTP_MOVED_TEMP == statusCode || HttpURLConnection.HTTP_MOVED_PERM == statusCode) {
				return getHttpsURLConnection(connection.getHeaderField("Location"), list);
			}

			return connection;
		} catch (MalformedURLException e) {
			throw new ITVException(context, ITVException.HTTP_GET_HTTPS_URL_CONN_MALFORMED_URL_EXCEPTION);
		} catch (IOException e) {
			throw new ITVException(context, ITVException.HTTP_GET_HTTPS_URL_CONN_IO_EXCEPTION);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw new ITVException(context, ITVException.HTTP_GET_HTTPS_URL_CONN_NO_SUCH_ALG_EXCEPTION);
		} catch (KeyManagementException e) {
			e.printStackTrace();
			throw new ITVException(context, ITVException.HTTP_GET_HTTPS_URL_CONN_KEYMANAGEMENT_EXCEPTION);
		}
	}

	private HttpURLConnection getHttpURLConnection(String type, String url, List<NameValuePair> list, int conTimeOut, int socTimeOut) throws ITVException {
		return getHttpURLConnection(type, url, list, conTimeOut, socTimeOut, false, true);
	}

	/**
	 * @param type
	 * @param url
	 * @param list
	 * @param conTimeOut
	 * @param socTimeOut
	 * @return
	 * @throws ITVException
	 */
	private HttpURLConnection getHttpURLConnection(String type, String url, List<NameValuePair> list, int conTimeOut, int socTimeOut, boolean flag, boolean retry) throws ITVException {
		LogUtil.i(TAG, "getHttpURLConnection type        = " + type);
		LogUtil.i(TAG, "getHttpURLConnection url         = " + url);
		LogUtil.i(TAG, "getHttpURLConnection conTimeOut  = " + conTimeOut);
		LogUtil.i(TAG, "getHttpURLConnection socTimeOut  = " + socTimeOut);

		disableConnectionReuseIfNecessary();
		if (null != list && "GET".equalsIgnoreCase(type)) {
			url = initGetUrl(url, list);
			LogUtil.i(TAG, "getHttpsURLConnection url         = " + url);
			list = null;
		}
		try {
			HttpURLConnection connection = (HttpURLConnection) (new URL(url)).openConnection(java.net.Proxy.NO_PROXY);
			if (null != list && !"GET".equalsIgnoreCase(type) && !flag) {
				for (NameValuePair nvp : list) {
					connection.setRequestProperty(nvp.getName(), nvp.getValue());
					LogUtil.i(TAG, "getHttpURLConnection list        = " + nvp.getName() + "=" + nvp.getValue());
				}
			}

			conTimeOut = (1 > conTimeOut) ? SET_CONNECTION_TIMEOUT : conTimeOut;
			socTimeOut = (1 > socTimeOut) ? SET_SOCKET_TIMEOUT : socTimeOut;

			connection.setConnectTimeout(conTimeOut);
			connection.setReadTimeout(socTimeOut);

			connection.setRequestMethod(type); // 默认就是GET
			if ("post".equalsIgnoreCase(type)) {
				connection.setDoInput(true);
				connection.setDoOutput(true);
			}
			connection.setDefaultUseCaches(false);
			connection.setInstanceFollowRedirects(true);// 设置本次连接是否自动处理重定向
			connection.connect();

			if (flag) {
				DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
//				String postContent = Util.encodeUrl(list, true);
				
				String postContent ="";
				if(url.equals(ConfigUtil.SERVER_URL)){
//					postContent = url + "?" + Util.encodeUrl(list, true);
					postContent = url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));//实现加密
				}else{
//					postContent = url + "?" + Util.encodeUrl(list, true);
					postContent = url+"?req="+TripleDesUtil.encode(HttpKeys.KEY_DES3, Util.encodeUrl(list, true));//实现加密

				}
				
				LogUtil.v(TAG, "postContent = " + postContent);
				dos.write(postContent.getBytes());
				dos.flush();
				dos.close();
			}

			int statusCode = connection.getResponseCode();
			/** 手动重定向操作 */
			if (HttpURLConnection.HTTP_MOVED_TEMP == statusCode || HttpURLConnection.HTTP_MOVED_PERM == statusCode) {
				LogUtil.i(TAG, "getHttpURLConnection HTTP_MOVED = " + connection.getHeaderField("Location"));

				return getHttpURLConnection(connection.getHeaderField("Location"), list);
			}

			return connection;
		} catch (MalformedURLException e) {
			throw new ITVException(context, ITVException.HTTP_GET_HTTP_URL_CONN_MALFORMED_URL_EXCEPTION);
		} catch (IOException e) {
			if (retry) {
				return getHttpURLConnection(type, url, list, conTimeOut, socTimeOut, flag, false);
			}
			else {
				throw new ITVException(context, ITVException.HTTP_GET_HTTP_URL_CONN_IO_EXCEPTION);
			}
		}
	}

	public HttpsURLConnection getHttpsURLConnection(String url, List<NameValuePair> list, int conTimeOut, int socTimeOut) throws ITVException {
		return getHttpsURLConnection("GET", url, list, conTimeOut, socTimeOut);
	}

	public HttpsURLConnection getHttpsURLConnection(String url, List<NameValuePair> list) throws ITVException {
		return getHttpsURLConnection(url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT);
	}

	public HttpURLConnection getHttpURLConnection(String url, List<NameValuePair> list, int conTimeOut, int socTimeOut) throws ITVException {
		return getHttpURLConnection("GET", url, list, conTimeOut, socTimeOut);
	}

	public HttpURLConnection getHttpURLConnection(String url, List<NameValuePair> list) throws ITVException {
		return getHttpURLConnection(url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT);
	}

	/**
	 * 根据参数url?param进行HTTP GET 请求，返回String
	 * 
	 * @param url
	 * @param param
	 * @param timeout
	 *            为true链接超时时间为5s，否则为2s;可参照get(List<NameValuePair>
	 *            list)默认链接超时时间为5s
	 * @return String
	 * @throws ITVException
	 * */
	public String get(String url, List<NameValuePair> list, int conTimeOut, int soketTimeout) throws ITVException {
		String result = "";
		if (url.startsWith("https")) {
			result = read(getHttpsURLConnection(url, list, conTimeOut, soketTimeout));
			if ((result.contains("\"code\":3,") || result.contains("\"code\":2001,") || result.contains("\"code\":-88403,") || result.contains("\"code\":-88107,")) && LoginMod.login(context)) {
				LogUtil.e(TAG, "SESSIONKEY INVALID : " + result);
				replaceSessionKey(list);
				result = read(getHttpsURLConnection(url, list, conTimeOut, soketTimeout));
			}
			return result;
		}
		else {
			result = read(getHttpURLConnection(url, list, conTimeOut, soketTimeout));
			if ((result.contains("\"code\":3,") || result.contains("\"code\":2001,") || result.contains("\"code\":-88403,") || result.contains("\"code\":-88107,")) && LoginMod.login(context)) {
				LogUtil.e(TAG, "SESSIONKEY INVALID : " + result);
				replaceSessionKey(list);
				result = read(getHttpURLConnection(url, list, conTimeOut, soketTimeout));
			}
			return result;
		}
	}

	private void replaceSessionKey(List<NameValuePair> list) {
		for (NameValuePair baskc : list) {
			if (baskc.getName().equals(HttpKeys.KEY_SESSIONKEY)) {
				list.remove(baskc);
				break;
			}

		}
		list.add(new BasicNameValuePair(HttpKeys.KEY_SESSIONKEY, ConfigUtil.SessionKey));
	}

	public String get(String url, List<NameValuePair> list) throws ITVException {
		return get(url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT);
	}

	public String get(List<NameValuePair> list) throws ITVException {
		return get(ConfigUtil.SERVER_URL, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT);
	}

	/**
	 * 根据参数url进行HTTP POST 请求，返回String
	 * 
	 * @param list
	 * @param url
	 * @param conTimeOut
	 * @param soketTimeout
	 * 
	 * @return String
	 * @throws ITVException
	 * */
	public String post(String url, List<NameValuePair> list, int conTimeOut, int soketTimeout, boolean flag) throws ITVException {
		if (url.startsWith("https"))
			return read(getHttpsURLConnection("POST", url, list, conTimeOut, soketTimeout));
		return read(getHttpURLConnection("POST", url, list, conTimeOut, soketTimeout, flag, true));
	}

	public String post(String url, List<NameValuePair> list, int conTimeOut, int soketTimeout) throws ITVException {
		return post(url, list, conTimeOut, soketTimeout, false);
	}

	public InputStream post(String url, List<NameValuePair> list) throws ITVException {
		if (url.startsWith("https"))
			return getInputStream(getHttpsURLConnection("POST", url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT));
		return getInputStream(getHttpURLConnection("POST", url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT));
	}

	public String post(List<NameValuePair> list) throws ITVException {
		return post(ConfigUtil.SERVER_URL, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT);
	}

	public String post(String url, List<NameValuePair> list, boolean flag) throws ITVException {
		return post(url, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT, flag);
	}

	public String post(List<NameValuePair> list, boolean flag) throws ITVException {
		return post(ConfigUtil.SERVER_URL, list, SET_CONNECTION_TIMEOUT, SET_SOCKET_TIMEOUT, flag);
	}

	public HttpClient getNewHttpClient(Context context) {
		try {
			KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
			trustStore.load(null, null);

			SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			HttpParams params = new BasicHttpParams();

			HttpConnectionParams.setConnectionTimeout(params, 10000);
			HttpConnectionParams.setSoTimeout(params, 10000);

			HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
			HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

			SchemeRegistry registry = new SchemeRegistry();
			registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
			registry.register(new Scheme("https", sf, 443));

			ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

			// Set the default socket timeout (SO_TIMEOUT) // in
			// milliseconds which is the timeout for waiting for data.
			HttpConnectionParams.setConnectionTimeout(params, 5000);
			HttpConnectionParams.setSoTimeout(params, 5000);
			HttpClient client = new DefaultHttpClient(ccm, params);
			WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			if (!wifiManager.isWifiEnabled()) {
				Uri uri = Uri.parse("content://telephony/carriers/preferapn");
				Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
				if (mCursor != null && mCursor.moveToFirst()) {
					String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
					if (proxyStr != null && proxyStr.trim().length() > 0) {
						HttpHost proxy = new HttpHost(proxyStr, 80);
						client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
					}
					mCursor.close();
				}
			}
			return client;
		} catch (Exception e) {
			return new DefaultHttpClient();
		}
	}

	public String readHttpResponse(HttpResponse response) throws ITVException {
		String result = "";
		try {
			InputStream inputStream = response.getEntity().getContent();
			Header header = response.getFirstHeader("Content-Encoding");
			if (header != null && header.getValue().toLowerCase(Locale.US).indexOf("gzip") > -1) {
				inputStream = new GZIPInputStream(inputStream);
			}
			ByteArrayOutputStream content = new ByteArrayOutputStream();

			// Read response into a buffered stream
			int readBytes = 0;
			byte[] sBuffer = new byte[1024 * 2];
			while ((readBytes = inputStream.read(sBuffer)) != -1) {
				content.write(sBuffer, 0, readBytes);
			}

			String content_type = response.getFirstHeader(HTTP.CONTENT_TYPE).getValue();
			String charset = null;
			if (-1 != content_type.indexOf("charset=")) {
				charset = content_type.substring(content_type.indexOf("charset=") + 8);
			}
			if (TextUtils.isEmpty(charset))
				result = new String(content.toByteArray(), HTTP.UTF_8).trim();
			else
				result = new String(content.toByteArray(), charset).trim();
		} catch (IOException e) {
			throw new ITVException(context, ITVException.HTTP_READ_HTTP_RESPONSE_IO_EXCEPTION);
		}
		return result;
	}

	private class MyTrustManager implements X509TrustManager {

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

		@Override
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}

	}

	private class MySSLSocketFactory extends SSLSocketFactory {
		SSLContext	sslContext	= SSLContext.getInstance("TLS");

		public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
			super(truststore);

			TrustManager tm = new X509TrustManager() {
				public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

				public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}

				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};

			sslContext.init(null, new TrustManager[] { tm }, null);
		}

		@Override
		public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
			return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
		}

		@Override
		public Socket createSocket() throws IOException {
			return sslContext.getSocketFactory().createSocket();
		}
	}
}
